#![allow(non_snake_case)]
use std::collections::HashMap;

use crate::{
    components::{ButtonList, CommonPage, DataRange},
    shhr::{
        del_shhr_dept, fetch_dept_menus, get_home_visit_flow, save_shhr_dept, Ygzygl,
    },
};
use icondata as i;
use leptos::prelude::*;
use leptos_icons::*;
use serde_json::{Map, Value};
use shq_common::prelude::{options::FetchParams, AndOr, FliterItem, Operator, User, WhereCause};
use shq_web_controls::{
    use_message, AutoSearch, MessageOptions, MessageVariant, MultiTreeSelect, ToastPosition,
    ToasterProvider,
};
use thaw_utils::ArcOneCallback;

#[component]
pub fn Ygxwgl(menu_id: u32, conf_name: Oco<'static, str>) -> impl IntoView {
    let conf_name = StoredValue::new(conf_name.to_string());
    let specialist_mana: RwSignal<bool> = RwSignal::new(false);
    let emid_value = RwSignal::new(String::new());
    let emid = RwSignal::new(u32::default());
    let dept_values = RwSignal::new(Vec::<u32>::new());
    let ny = RwSignal::new(u32::default());
    let selected_dpid = RwSignal::new(u32::default());
    let selected_wfid = RwSignal::new(u32::default());
    let selected_emid = RwSignal::new(u32::default());
    let release: RwSignal<bool> = RwSignal::new(false);
    let error_message = RwSignal::new(None::<String>);
    let saving = RwSignal::new(false);
    let specialist_delete = RwSignal::new(false);
    let is_refresh = RwSignal::new(false);
    let mess = use_message();
    let curr_user = use_context::<RwSignal<Option<User>>>().unwrap();
    let save_dept_action = Action::new(move |dpids: &Vec<u32>| {
        let ny_val = ny.get();
        let dpids = dpids.clone();
        let userid = curr_user
        .with(|u| u.as_ref().map(|u| u.id))
        .unwrap_or_default();
        async move {
            match get_home_visit_flow(ny_val, userid, dpids.to_vec()).await {
                Ok(_) => {
                    mess.create(
                        "保存成功",
                        MessageVariant::Success,
                        MessageOptions::default(),
                    );
                    release.set(false);
                    ny.set(ny.get());
                }
                Err(e) => {
                    mess.create(
                        format!("保存失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default(),
                    );
                }
            }
            release.set(false);
            set_timeout(
                move || error_message.set(None),
                std::time::Duration::from_secs(300),
            );
        }
    });
    let delete_user_action = Action::new(move |&(emid, dpid): &(u32, u32)| {
        let ny_val = ny.get();
        let wfid = selected_wfid.get();
        async move {
            error_message.set(None);
            saving.set(true);
            if emid == 0 {
                error_message.set(Some("请选择审批专员".to_string()));
                saving.set(false);
                return;
            }
            match del_shhr_dept(ny_val, wfid, emid, dpid).await {
                Ok(_) => {
                    mess.create(
                        "删除成功",
                        MessageVariant::Success,
                        MessageOptions::default(),
                    );
                    is_refresh.set(true);
                    ny.set(ny.get());
                }
                Err(e) => {
                    mess.create(
                        format!("删除失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default(),
                    );
                }
            }
            saving.set(false);
        }
    });
    let custom_specialist_mana = ArcOneCallback::new(move |_| specialist_mana.set(true));
    let delete_specialist_mana = ArcOneCallback::new(move |rows:Vec<Value>| {
        let row=rows[0].as_object().unwrap();
        let jemid=row.get("emid").expect("返回值没有emid");
        let jdpid=row.get("dpid").expect("返回值没有dpid");
        let emid=jemid.as_u64().expect("emid不是u64类型");
        let dpid=jdpid.as_u64().expect("dpid不是u64类型");
        delete_user_action.dispatch((emid as u32, dpid as u32));
    });
    let release_specialist_mana = ArcOneCallback::new(move |rows:Vec<Value>| {
        if !rows.is_empty()  {
            let mut dpids = Vec::new();
            for row in rows {
                if let Some(obj) = row.as_object() {
                    if let Some(jdpid) = obj.get("dpid") {
                        if let Some(dpid) = jdpid.as_u64() {
                            dpids.push(dpid as u32);
                        }
                    }
                }
            }
            if !dpids.is_empty() {
                save_dept_action.dispatch(dpids);
            } else {
                mess.create(
                    "选择的记录中没有有效的部门ID",
                    MessageVariant::Warning,
                    MessageOptions::default(),
                );
            }
        }else{
            mess.create(
                "没有选择任何数据",
                MessageVariant::Warning,
                MessageOptions::default(),
            );
        }
    });
    // 定义自定义按钮
    let custom_buttons = {
        let mut bl = ButtonList::new();
        if conf_name.get_value() == "jf" {
            bl.add_custom(
                "发布".to_string(),
                Some(i::SiSemanticrelease),
                None,
                Some("您确定要发布吗？".to_string()),
                DataRange::All,
                vec!["dpid"],
                release_specialist_mana,
            );
        }
        bl.add_custom(
            "新增".to_string(),
            Some(i::AiPlusCircleOutlined),
            None,
            None,
            DataRange::None,
            Vec::new(),
            custom_specialist_mana,
        );
        bl.add_custom(
            "删除".to_string(),
            Some(i::AiDeleteTwotone),
            None,
            Some("您确定要删除选择的部门吗？".to_string()),
            DataRange::Selected,
            vec!["emid","dpid"],
            delete_specialist_mana,
        );
        bl
    };
    let conf_name1 = if conf_name.get_value() == "jf" {
        "dept_approvers2".to_string()
    } else {
        "dept_approvers".to_string()
    };
    let dept_items = Resource::new(move || (), |_| async { fetch_dept_menus().await });
    let on_change = move |values: Vec<String>| {
        let u32_values: Vec<u32> = values.iter().map(|v| v.parse().unwrap()).collect();
        dept_values.set(u32_values);
    };
    // 将所选择的年月
    let on_tolbar_params_change = ArcOneCallback::new(move |params: HashMap<String, String>| {
        if let Some(ny_str) = params.get("ny") {
            if let Ok(ny_val) = ny_str.parse::<u32>() {
                ny.set(ny_val);
            }
        }
    });
    // 将所选中的部门ID
    let on_row_select_change =
        ArcOneCallback::new(move |selected_rows: Option<Map<String, Value>>| {
            if let Some(rows) = selected_rows {
                if let Some(Value::Number(dpid_value)) = rows.get("dpid") {
                    if let Some(int_dpid) = dpid_value.as_u64().map(|x| x as u32) {
                        selected_dpid.set(int_dpid);
                    }
                }
                if let Some(Value::Number(wfid_value)) = rows.get("wfid") {
                    if let Some(int_wfid) = wfid_value.as_u64().map(|x| x as u32) {
                        selected_wfid.set(int_wfid);
                    }
                }
                if let Some(Value::Number(emid_value)) = rows.get("emid") {
                    if let Some(int_emid) = emid_value.as_u64().map(|x| x as u32) {
                        selected_emid.set(int_emid);
                    }
                }
            }
        });
    let on_change_user = move |value: Option<String>| {
        if let Some(v) = value {
            if let Ok(int_emid) = v.parse::<u32>() {
                emid.set(int_emid);
            } else {
                emid.set(0); // 或者其他的默认值
            }
        } else {
            emid.set(0); // 或者其他默认值
        }
    };
    let wfid = if conf_name.get_value() == "jyls" {
        2 as u32
    } else if conf_name.get_value() == "jf" {
        3 as u32
    } else {
        1 as u32
    };
    // 保存
    let save_user_action = Action::new(move |_: &()| {
        let emid_val = emid.get();
        let dept_values_val = dept_values.get();
        let ny_val = ny.get();
        async move {
            error_message.set(None);
            saving.set(true);
            if emid_val == 0 {
                error_message.set(Some("请选择审批专员".to_string()));
                saving.set(false);
                return;
            }
            if dept_values_val.is_empty() {
                error_message.set(Some("请至少选择一个部门".to_string()));
                saving.set(false);
                return;
            }
            match save_shhr_dept(ny_val, wfid, emid_val, dept_values_val).await {
                Ok(_) => {
                    mess.create(
                        "保存成功",
                        MessageVariant::Success,
                        MessageOptions::default(),
                    );
                    emid.set(0);
                    emid_value.set(String::new());
                    dept_values.set(Vec::new());
                    is_refresh.set(true);
                    ny.set(ny.get());
                    specialist_mana.set(false);
                }
                Err(e) => {
                    mess.create(
                        format!("保存失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default(),
                    );
                }
            }
            saving.set(false);
            set_timeout(
                move || error_message.set(None),
                std::time::Duration::from_secs(300),
            );
        }
    });
    // 专员删除
    let specialist_delete_management = move || {
        if specialist_delete.get() {
            Some(view! {
                <dialog id="delete_confirm_modal" class="modal modal-open z-50">
                    <div class="modal-box max-w-md">
                        <button class="absolute right-2 top-2" on:click=move|_|{
                            specialist_delete.set(false);
                        }>
                            <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
                        </button>
                        <div class="flex items-center mb-4">
                            <Icon icon=i::AiExclamationCircleOutlined/>
                            <h3 class="text-lg font-bold">确认删除</h3>
                        </div>
                        <div class="p-2">
                            <p class="text-gray-700 mb-6">
                                "你确定要删除选中的审批专员配置吗？此操作不可撤销。"
                            </p>
                            {/* 底部操作按钮 */}
                            <div class="mt-4 flex justify-end gap-2">
                                <button
                                    class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                    on:click=move|_| specialist_delete.set(false)
                                >
                                    取消
                                </button>
                                <button
                                    class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                                    on:click=move|_| {
                                        specialist_delete.set(false);
                                        delete_user_action.dispatch((selected_emid.get(), selected_dpid.get()));
                                    }
                                >
                                    确认删除
                                </button>
                            </div>
                        </div>
                    </div>
                </dialog>
            })
        } else {
            None
        }
    };
    // 专员新增页面
    let specialist_management = move || {
        if specialist_mana.get() {
            Some(view! {
                <dialog id="data_import_modal" class="modal modal-open  z-50">
                    <div class="modal-box overflow-hidden max-w-3xl">
                        <button class="absolute right-2 top-2" on:click=move|_|{
                            specialist_mana.set(false);
                        }>
                            <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
                        </button>
                        <h3 class="text-lg font-bold">新增员工行为管理</h3>
                        <div class="p-2">
                            <div class="w-full">
                                <AutoSearch
                                    label="审批专员"
                                    value={let v = emid_value.get(); if v.is_empty() { None } else { Some(v) }}
                                    fetch_params=StoredValue::new(FetchParams {
                                        table_name: "v_user_name".to_string(),
                                        label_col: "name".to_string(),
                                        value_col: "id".to_string(),
                                        parent_col: None,
                                        where_cause: Some("name".to_string()),
                                        order_by: Some("id".to_string()),
                                        search_cols: Some(vec!["name".to_string()]),
                                    })
                                    on_change=on_change_user
                                    err_msg = " "
                                />
                            </div>
                            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                                {move || match dept_items.get() {
                                    Some(Ok(dept)) => {
                                        let tree_items = StoredValue::new(dept.into());
                                        view! {
                                            <div class="flex-1 overflow-y-auto min-h-40">
                                                <MultiTreeSelect
                                                    tree_items
                                                    show_confirm_cancel_btn=false
                                                    on_change
                                                    height= 200
                                                />
                                            </div>
                                        }.into_any()
                                    }
                                    Some(Err(e)) => {
                                        view! {
                                            <div class="p-4 text-red-500">
                                                {e.to_string()}
                                            </div>
                                        }.into_any()
                                    }
                                    None => {
                                        view! {
                                            <div class="flex-1 flex items-center justify-center">
                                                "正在加载菜单数据..."
                                            </div>
                                        }.into_any()
                                    }
                                }}
                            </Suspense>
                            {/* 底部操作按钮 */}
                            <div class="mt-4 flex justify-end gap-2">
                                <button
                                    class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                    on:click=move|_| specialist_mana.set(false)
                                >
                                    取消
                                </button>
                                <button
                                    class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                    on:click=move|_| {
                                        specialist_mana.set(false);
                                        save_user_action.dispatch(());
                                    }
                                >
                                    确认
                                </button>
                            </div>
                        </div>
                    </div>
                </dialog>
            })
        } else {
            None
        }
    };
    // 发布页面
    // let release_page = move || {
    //     release.get().then(||
    //     view! {
    //             <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    //                 <div class="bg-white rounded-lg p-6 max-w-md w-full">
    //                     <h3 class="text-lg font-medium text-gray-900 mb-4">"确认发布"</h3>
    //                     <p class="text-gray-700 mb-6">"你确定要发布当前流程吗?"</p>
    //                     <div class="flex justify-end space-x-4">
    //                         <button
    //                             class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition-colors"
    //                             on:click=move |_| release.set(false)
    //                         >
    //                             "取消"
    //                         </button>
    //                         <button
    //                             class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
    //                             on:click=move |_| {
    //                                 release.set(false);
    //                                 save_dept_action.dispatch(());
    //                             }
    //                         >
    //                             "确认发布"
    //                         </button>
    //                     </div>
    //                 </div>
    //             </div>
    //         })
    // };
    let init_filters = Signal::derive(move || {
        vec![WhereCause {
            field_name: "wfid".to_string(),
            filter_items: vec![FliterItem {
                operator: Operator::In,
                value: Some(wfid.to_string()),
            }],
            and_or: AndOr::And,
        }]
    });
    view! {
        <div class="flex flex-1 gap-2 mx-2 w-full h-full overflow-hidden">
            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                <CommonPage
                    menu_id=menu_id
                    conf_name=conf_name1.clone()
                    custom_buttons=custom_buttons
                    on_tolbar_params_change=on_tolbar_params_change
                    on_row_select_change=on_row_select_change
                    init_filters
                />
                {move || {
                    let conf = conf_name.get_value();
                    if conf == "jyls" || conf == "xdbg" {
                        Some(view! { <Ygzygl menu_id ny wfid/> }.into_any())
                    } else {
                        None
                    }
                }}
                <ToasterProvider position=ToastPosition::TopStart>
                    {specialist_delete_management}
                    {specialist_management}
                    // {release_page}
                </ToasterProvider>
            </Suspense>
        </div>
    }.into_any()
}
